package utils

import (
	"net"
	"net/http"
	"strings"
)

const(
	xforwardedfor = "X-Forwarded-For"
	xrealip = "X-Real-Ip"
)

func GetClientIp(req *http.Request) string {
	// 先获取X-Forwarded-For的第一个
	if ip := strings.TrimSpace(strings.Split(req.Header.Get(xforwardedfor),",")[0]); ip!="" {
		return ip
	}
	// "X-Real-Ip"
	if ip := req.Header.Get(xrealip); ip!="" {
		return ip
	}
	// 若 req.RemoteAddr 格式化成功 则返回
	if ip,_,error := net.SplitHostPort(strings.TrimSpace(req.RemoteAddr));error==nil {
		return ip
	}
	return ""
}